﻿using AutoMapper;
using MediatR;
using WMS_Goodsinfo.Api.Write.Application.Command.商品;
using WMS_Goodsinfo.Domain;
using WMS_Goodsinfo.ErrorCode;
using WMS_Goodsinfo.Infastructure;

namespace WMS_Goodsinfo.Api.Write.Application.Handler.商品
{
    public class CreateProductHandler : IRequestHandler<CreateProductCommand, ApiResult<int>>
    {
        private readonly IProductRepository<Product_Table> _productRepo;
        private readonly IMapper _mapper;
        private readonly ILogger<CreateProductHandler> logger;

        public CreateProductHandler(IProductRepository<Product_Table> productRepo, IMapper mapper, ILogger<CreateProductHandler> logger)
        {
            _productRepo = productRepo;
            _mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 添加商品信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(CreateProductCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var model =_mapper.Map<Product_Table>(request);
            model.CreateTime=DateTime.Now;

            var list = _productRepo.GetAll().Where(p => p.ProductName == request.ProductName);
            if (list.Any())
            {
                result.Code = StatusEnum.Error;
                result.Message = "商品名称已存在";
                return Task.FromResult(result);
            }
            var res =_productRepo.Add(model);
            if(res>0)
            {
                result.Code = StatusEnum.OK;
                result.Data = res;
                result.Message = "添加商品成功";
                logger.LogInformation("添加商品信息成功");

            }
            else
            {
                result.Code = StatusEnum.Fail;
                result.Data = res;
                result.Message = "添加商品失败";
                logger.LogError("添加商品信息失败");
            }
            return Task.FromResult(result);
        }
    }
}
